
#include <stdlib.h>
#include <string.h>
#include "circular-queue.h"

int InitQueue(CirQueue *queue){
    if (queue){
        queue->front = 0;
        queue->rear = 0;
        queue->data = malloc((MAX_QUEUE_SIZE+1)*sizeof(ElemType));
        queue->capacity = MAX_QUEUE_SIZE;
        return(0);
    }else{
        return(-1);
    }
}

int DestroyQueue(CirQueue *queue){
    if (queue && queue->data){
        queue->front = 0;
        queue->rear = 0;
        queue->capacity = 0;
        free(queue->data);
        return(0);
    } else{
        return(-1);
    }
}

int ClearQueue(CirQueue *queue){
    if (queue && queue->data){
        queue->front = 0;
        queue->rear = 0;
        return(0);
    }else{
        return(-1);
    }
}

int QueueEmpty(CirQueue queue){
    return(queue.front == queue.rear);
}

int GetHead(CirQueue queue,ElemType *element){
    if (queue.data){
        memcpy(element,queue.data+queue.front, sizeof(ElemType));
        return(0);
    }else{
        return(-1);
    }
}

int EnQueue(CirQueue *queue,ElemType element){
    if (queue && queue->data && (queue->rear+1 )%(queue->capacity + 1) != queue->front){

        memcpy(queue->data+queue->rear,&element, sizeof(ElemType));
        queue->rear = (queue->rear+1)%(queue->capacity + 1);

        return(0);
    } else{
        return(-1);
    }
}
int DeQueue(CirQueue *queue,ElemType *element){
    if (queue->rear != queue->front){

        memcpy(element,queue->data+queue->front, sizeof(ElemType));
        queue->front = (queue->front+1)%(queue->capacity + 1);

        return(0);
    } else{
        return(-1);
    }
}

int QueueLength(CirQueue queue){
    return((int)((queue.rear - queue.front + queue.capacity)%(queue.capacity+1))+1);
}